package com.st.buy.content.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.st.buy.content.service.ContentCategoryService;
import com.st.buy.manager.mapper.TbContentCategoryMapper;
import com.st.buy.pojo.TbContentCategory;
import com.st.buy.util.pojo.EasyUITreeNode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author 张双虎
 */
@Service
public class ContentCategoryServiceImpl implements ContentCategoryService {
    @Autowired
    private TbContentCategoryMapper contentCategoryMapper;
    @Override
    public List<EasyUITreeNode> queryCatByPid(long pid) {
        List<EasyUITreeNode> nodes = new ArrayList<>();
        //准备查询条件
        QueryWrapper<TbContentCategory> wrapper = new QueryWrapper<TbContentCategory>();
        //条件是 paretn_id = #{pid}
        wrapper.eq("parent_id",pid);
        wrapper.eq("status",1);
        List<TbContentCategory> cats = contentCategoryMapper.selectList(wrapper);
        //将itemCatList转换为EasyUITreeNodeList
        for (TbContentCategory cat : cats) {
            EasyUITreeNode node = new EasyUITreeNode();
            node.setId(cat.getId());
            node.setText(cat.getName());
            node.setState(cat.getParent()?"closed":"open");
            nodes.add(node);
        }
        return nodes;
    }

    @Override
    public TbContentCategory save(TbContentCategory contentCategory) {
        //补全数据
        contentCategory.setStatus(1);
        contentCategory.setSortOrder(1);
        contentCategory.setParent(false);
        Date time = new Date();
        contentCategory.setCreated(time);
        contentCategory.setUpdated(time);
        //保存对象，保存完成之后，会将自增列的id直接回填到要保存的对象中
        contentCategoryMapper.insert(contentCategory);
        return contentCategory;
    }

    @Override
    public void update(TbContentCategory contentCategory) {
        contentCategoryMapper.updateById(contentCategory);
    }

    @Override
    public void delete(long catId) {
        TbContentCategory contentCategory = new TbContentCategory();
        contentCategory.setId(catId);
        contentCategory.setStatus(2);//修改状态为2，表示删除
        contentCategoryMapper.updateById(contentCategory);
    }
}
